package com.demo2do.fms.admin.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zaxxer.hikari.HikariDataSource;
import com.zaxxer.hikari.HikariPoolMXBean;

/**
 *
 * @author Ark
 *
 */
public class ConnectionPoolInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionPoolInterceptor.class);
    
    @Value("#{config['shell.shutdown']}")
    private String shellShutdown;
    
    @Autowired
    private HikariDataSource dataSource;
    
    /* (non-Javadoc)
     * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        HikariPoolMXBean hikariPoolMXBean = dataSource.getHikariPoolMXBean();
        int idleConnections = hikariPoolMXBean.getIdleConnections();
        
        if (idleConnections == 2) {
            
            try {
                
                synchronized (this) {
                    if (!dataSource.isClosed()) {
                        logger.warn("#preHandle() - idle connection empty, restart program...");
                        Runtime.getRuntime().exec(shellShutdown).waitFor();
                    }
                }
                
            } catch (Exception e) {
                logger.error("#preHandle() - restart program occur error=[{}]", e);
            }
            
        }
        
        return super.preHandle(request, response, handler);
        
    }
    
}
